<template>
  <div>
    <h2>随机点名</h2>
    <div class="box">
      <span>名字是：</span>
      <div class="qs">{{ result }}</div>
    </div>
    <div class="btns">
      <button class="start" @click="start()">开始</button>
      <button class="end" @click="close()">结束</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      result: "这里显示姓名",
      name: [
        "胡斐",
        "狄云",
        "萧峰",
        "郭靖",
        "马家骏",
        "韦小宝",
        "令狐冲",
        "陈家洛",
        "杨过",
        "石破天",
        "张无忌",
        "袁承志",
        "袁冠南",
      ],
      // 流程控制开关
      open: true,
      // 定义计时器开关
      timer: null,
    };
  },
  methods: {
    move() {
      // 获取一个 0-当前数组长度的随机数
      let random = Math.floor(Math.random() * (this.name.length - 0));

      // 让随机数成为数组的随机下标，赋值给 result ，在页面渲染
      this.result = this.name[random];
    },
    start() {
      // 流程控制开关
      // 定义计时器，调用move方法
      this.timer = setInterval(this.move, 100);
      this.open = false;
    },
    close() {
      // 清除计时器
      clearInterval(this.timer);
      this.open = true;
    },
  },
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
}

h2 {
  text-align: center;
}

.box {
  width: 600px;
  margin: 50px auto;
  display: flex;
  font-size: 25px;
  line-height: 40px;
}

.qs {
  width: 450px;
  height: 40px;
  color: red;
}

.btns {
  text-align: center;
}

.btns button {
  width: 120px;
  height: 35px;
  margin: 0 50px;
}
</style>